import { VNode } from 'preact';
import Cherry from 'cherry-markdown';
import { useSignal } from '@preact/signals';
import { useEffect } from 'preact/hooks';
import { Namespace, createUUID } from '../../../utils';
import { IChatMessage } from '../../../interface';
import { AiChatController } from '../../../controller';
import './markdown-message.scss';

export interface MarkdownMessageProps {
  /**
   * 单实例聊天总控
   *
   * @author chitanda
   * @date 2023-10-13 17:10:43
   * @type {AiChatController}
   */
  controller: AiChatController;
  message: IChatMessage;
  /**
   * 内容大小，用于更新绘制
   *
   * @author chitanda
   * @date 2023-10-15 21:10:22
   * @type {number}
   */
  size: number;
  /**
   * 工具栏
   *
   * @type {VNode}
   * @memberof MarkdownMessageProps
   */
  children: VNode;
}

const ns = new Namespace('markdown-message');

export const MarkdownMessage = (props: MarkdownMessageProps) => {
  const { message, size } = props;

  const uuid = useSignal(createUUID());

  const cherry = useSignal<Cherry | null>(null);

  useEffect(() => {
    if (size >= 0 && cherry.value) {
      cherry.value.setMarkdown(message.content);
    }
  }, [message, size]);

  useEffect(() => {
    cherry.value = new Cherry({
      id: uuid,
      value: message.content,
      editor: {
        defaultModel: 'previewOnly',
      },
    });
  }, []);

  return (
    <div className={`${ns.b()} ${ns.is('loading', message.state === 20)}`}>
      <div className={ns.b('header')}>
        <div className={ns.be('header', 'caption')}>AI </div>
        {props.children}
      </div>
      <div className={`${ns.b('content')} pre-wrap-container`}>
        <div id={uuid} />
      </div>
      <div className={ns.b('footer')}></div>
    </div>
  );
};
